package com.example.constellation.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.constellation.bean.StarBean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*

读取Assets文件夹中的数据的工具类



 */
public class AssetsUtils {
    /*读取assets文件夹中的内容 存放到字符串当中
     */
    private static Map<String,Bitmap>logoImgMap;
    private static Map<String,Bitmap>contentlogoImgMap;



    public static String getJsonFromAssets(Context context,String filename)
    {
        //获取Assets文件夹管理器
        AssetManager am= context.getAssets();
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        //2.获取输入流
        try {
            InputStream is=am.open(filename);
                    int hasRead =0;
            byte[] buf=new byte[1024];
            while(true)
            {
                hasRead= is.read(buf);
                if(hasRead==-1)
                {
                    break;
                }
                byteArrayOutputStream.write(buf,0,hasRead);
            }
            String msg=byteArrayOutputStream.toString();
            is.close();
            return msg;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
    读取Assets文件夹下的图片 返回bitmap对象
     */

    public static Bitmap getBitmapFromAssets(Context context,String filename){
        Bitmap bitmap=null;
        //获取文件夹管理者
        AssetManager assets = context.getResources().getAssets();
        try {
            InputStream inputStream=assets.open(filename);
            //通过位图管理器 将输入流转换成位图对象
            bitmap= BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return bitmap;
    }


    /*
    将Assets文件夹当中的图片一起读取，放置在内存中，便于管理
     */
    public static void saveBitmapFromAssets(Context context, StarBean starInfoBean)
    {
        logoImgMap=new HashMap<>();
        contentlogoImgMap=new HashMap<>();
        List<StarBean.StarinfoBean> starinfoBeanList=starInfoBean.getStarinfo();
        for(int i=0;starinfoBeanList.size()>i;i++)
        {
            String logoname=starinfoBeanList.get(i).getLogoname();
            String filename="xzlogo/"+logoname+".png";
            Bitmap logobm=getBitmapFromAssets(context,filename);
            logoImgMap.put(logoname,logobm);
            String contentName="xzcontentlogo/"+logoname+".png";
            Bitmap bitmap=getBitmapFromAssets(context,contentName);
            contentlogoImgMap.put(logoname,bitmap);

        }
    }

    public static Map<String, Bitmap> getContentlogoImgMap() {
        return contentlogoImgMap;
    }

    public static Map<String, Bitmap> getLogoImgMap() {
        return logoImgMap;
    }
}
